from flask import Flask, jsonify
import time
import threading
from datetime import datetime, timedelta
import uuid

app = Flask(__name__)

task_progress = 0
task_start_time = None
task_thread = None

TASK_TOTAL_TIME = 20

def run_task():
    global task_progress, task_start_time
    task_start_time = datetime.now()
    end_time = task_start_time + timedelta(seconds=TASK_TOTAL_TIME)
    while datetime.now() < end_time:
        elapsed = (datetime.now() - task_start_time).total_seconds()
        task_progress = min(100, (elapsed / TASK_TOTAL_TIME) * 100)
        time.sleep(0.2)
    task_progress = 100

@app.route('/')
def index():
    return 'Py-test service'

@app.route('/meta')
def meta():
    return jsonify({
        'name': 'py-test',
        'description': 'this is a test service',
        'category': 'test',
    })

@app.route('/tasks')
def get_tasks():
    return jsonify({
        'tasks': [
            'test: Void -> Void'
        ]
    })

@app.route('/workflows')
def get_workflows():
    return jsonify({
        'workflows': []
    })

@app.route('/mount', methods=['POST'])
def mount():
    return str(uuid.uuid4())


@app.route('/task/test')
def start_task():
    global task_thread, task_progress
    task_progress = 0
    task_thread = threading.Thread(target=run_task)
    task_thread.daemon = True
    task_thread.start()
    id = str(uuid.uuid4())
    return jsonify({
        'task_id': id,
        'progress_pipe_addr': f'/task/test/progress/{id}',
        'result_addr': f'/task/test/result/{id}'
    })

@app.route('/task/test/progress/<task_id>')
def get_progress(task_id):
    global task_thread, task_progress

    if task_thread is None or not task_thread.is_alive():
        return jsonify({
            'status': "Completed",
            'percentage': 100
        })
    
    return jsonify({
        'status': "Running",
        'percentage': int(task_progress)
    })

@app.route('/task/test/result/<task_id>')
def get_result(task_id):
    return jsonify({
        'result': 'success'
    })

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)
